<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Date: 2017/2/23
 * Time: 15:12
 */
namespace app\controllers;

use app\base\BaseService;
use yii;
use yii\web\Controller;
use yii\web\Response;
use yii\base\Exception;
use app\services\OrgUserService;
use app\utils\ExcelHandler\ExcelHandler;
use app\base\BaseController;
use app\utils\QiniuUtil;
use app\services\PictureService;

class ExpandController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * 控制器初始化
     */
    public function init()
    {
        //跨域
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,sign,timeNumber,random");
        header('Access-Control-Allow-Methods: GET, POST');
        //ajax返回json
        Yii::$app->response->format = Response::FORMAT_JSON;
    }

    /**
     * 统一JSON返回
     * @param $errIndex
     * @param array $data
     * @return array
     * @throws Exception
     */
    protected function ajaxReturn($errIndex, $data = [])
    {

        if (empty(Yii::$app->params['error'][$errIndex])) {
            $errorMsg = json_encode([
                'code' => Yii::$app->params['error']['params_error']['code'],
                'message' => "未找到返回信息索引[{$errIndex}]",
                'data' => [],
            ],JSON_UNESCAPED_UNICODE);
            throw new Exception($errorMsg);
        }
        $error = Yii::$app->params['error'][$errIndex];
        //var_dump($error);die;
        return [
            'code' => $error['code'],
            'message' => $error['info'],
            'data' => $data
        ];
    }

    /**
     * @return array
     * 模版下载--链接
     */
    public function actionDownload()
    {
        $time = Yii::$app->request->get("time");
        $sign = Yii::$app->request->get("sign");
        $times = time();
        try {
            if ($sign != md5($time."10086")) {
                return $this->ajaxReturn('operate_permission_error', []);
            }
            if ($time > $times) {
                OrgUserService::getInstance()->downloads();
                return $this->ajaxReturn('success', []);
            } else {
                return $this->ajaxReturn('url_failure', []);
            }
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }
    /**
     * 导入
     * by dt
     */
    public function actionImport()
    {
        $data = [
            'type' => Yii::$app->request->post("type"),//类型
            'token' => Yii::$app->request->post("token"),//token
            'branchId' => Yii::$app->request->post("branchId"),//分部ID
            'deptId' => Yii::$app->request->post("deptId"),//部门ID
            'postId' => Yii::$app->request->post("postId"),//岗位ID
            'appSys' => Yii::$app->request->post("appSys"),//开通系统信息
            'permissions' => Yii::$app->request->post("permissions"),//角色信息
            'superiorLeaderShipId' =>Yii::$app->request->post("superiorLeaderShipId"),//上级领导人ID
        ];
        try {
            OrgUserService::getInstance()->checkForm($data, 'import');
            BaseController::$token = $data['token'];
            $objectPHPExcel = ExcelHandler::getInstance();
            $phpexcel = $objectPHPExcel->load('fileDemo',0,'');
            $sheetSize = $phpexcel->getSheetSize();
            $invoiceExcelData = $phpexcel->read($colStart = 'A', $rowStart = 2, $sheetSize['column'], $sheetSize['row']);//第二行开始，去掉第一行字段说明
            //处理上传的文件
            $post = OrgUserService::getInstance()->dealExcel($invoiceExcelData, $data);
            switch ($data['type']) {
                case "1":
                    $res = OrgUserService::getInstance()->importAdd($post);
                    $return_type = 'add';
                    break;
                case "2":
                    $res = OrgUserService::getInstance()->importCover($post);
                    $return_type = 'cover';
                    break;
                default:
                    $res =  [];
                    $return_type = '';
                    break;
            }
            if (!empty($res['result'] )) {
                return self::ajaxReturn('import_'.$res['result'].'_'.$return_type);
            }
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }

    /**
     * 验证码
     * @author dt
     * @time 2017/1/18
     */
    public function actionCode()
    {
        $mobile = $_POST['account'];
        BaseService::getInstance()->Code($mobile);
    }

    /**
     * 上传图片到七牛
     * @author dt
     */
    public function actionUploadPic(){
        try {
            $token = Yii::$app->request->post("token");
            if (!$token) {
                return self::ajaxReturn('token_missing');
            }
            BaseController::$token = Yii::$app->request->post("token");
            $qiniu = QiniuUtil::getInstance();
            $res = $qiniu->upload('img');
            if ($res['status'] != '0') {
                return self::ajaxReturn('import_Fail');
            }
            $data = [
                'imageUrl' => $res['data']['key'],
                'imageType' => Yii::$app->request->post("imageType"),
                'imageBelongType' => Yii::$app->request->post("imageBelongType"),
                'belongId' => Yii::$app->request->post("belongId"),
                'imageDesc' => Yii::$app->request->post("imageDesc")
            ];
            $result = PictureService::getInstance()->add($data);
            return self::ajaxReturn('operate_success_add',$result);
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }
}